<template>
  <div :style="paddingStyle">
    <div
      v-if="hiddenEdit && !hideAdd"
      style="
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: flex-end;
        margin: 0 0 16px 0;
      "
    >
      <el-button
        @click="showSelect = true"
        type="primary"
        icon="el-icon-goods"
        size="medium"
        >（{{ arrTotal.length }}）已选择</el-button
      >
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="handleSelect"
        size="medium"
        >确认添加</el-button
      >
    </div>
    <div class="topiclist_content">
      <div class="topiclist_content_left">
        <el-collapse v-model="activeName">
          <el-collapse-item
            :name="item.value"
            v-for="(item, index) in categoryTree"
            :key="index"
          >
            <template slot="title">
              <div
                class="tree_parent"
                @click="changeSelected(item, 'parent')"
                :class="{
                  select_bg: selectedId == item.value,
                  tree_top: index == 0,
                }"
              >
                <img
                  v-if="index != 0"
                  :class="[
                    activeName.includes(item.value) ? 'arrow90' : '',
                    'arrow',
                  ]"
                  src="@/assets/images/courseadd/pickup.png"
                  alt=""
                />
                <img
                  v-if="index == 0"
                  class="arrows"
                  src="@/assets/images/courseadd/pickup.png"
                  alt=""
                />
                <el-checkbox
                  v-if="hiddenEdit && !hideAdd"
                  :disabled="true"
                  :indeterminate="item.isIndeterminate"
                  v-model="item.checkAll"
                ></el-checkbox
                ><span
                  style="
                    margin-left: 10px;
                    width: 280px;
                    display: inline-block;
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                  "
                  >{{ item.label }}</span
                >
              </div>
            </template>
            <div
              @click="changeSelected(childItem, 'child')"
              :class="{ select_bg: selectedId == childItem.value }"
              class="tree_child"
              v-for="(childItem, childIndex) in item.children"
              :key="childIndex"
            >
              <el-checkbox
                v-if="hiddenEdit && !hideAdd"
                :disabled="true"
                :indeterminate="childItem.isIndeterminate"
                v-model="childItem.checkAll"
              ></el-checkbox
              ><span
                style="
                  margin-left: 10px;
                  width: 280px;
                  display: inline-block;
                  overflow: hidden;
                  white-space: nowrap;
                  text-overflow: ellipsis;
                "
                >{{ childItem.label }}</span
              >
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
      <div class="topiclist_content_right">
        <div class="myTopicList">
          <div style="display: flex; margin-bottom: 10px">
            <el-input
              style="width: 160px"
              @change="getList(false)"
              class="search"
              v-model="queryParams.searchWord"
              placeholder="请输入类型"
              clearable
            ></el-input>
            <!-- <el-select
              style="width: 160px"
              @change="getList(false)"
              class="search"
              v-model="queryParams.searchWord"
              placeholder="请选择类型"
              clearable
            >
              <el-option label="考核" value="考核" />
              <el-option label="练习" value="练习" />
              <el-option label="作业" value="作业" />
              <el-option label="抽查" value="抽查" />
            </el-select> -->
            <el-select
              style="width: 160px"
              v-if="!isOfflineExam && !showAll"
              @change="getList(false)"
              class="search"
              v-model="queryParams.topicType"
              placeholder="请选择题型"
              clearable
            >
              <el-option
                v-for="dict in dict.type.topic_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
            <el-select
              style="width: 160px"
              v-if="showAll"
              @change="getList(false)"
              class="search"
              v-model="queryParams.topicType"
              placeholder="请选择题型"
              clearable
            >
              <el-option
                v-for="dict in dict.type.topic_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
            <el-input
              style="width: 160px"
              @change="getList(false)"
              class="search"
              v-model="queryParams.content"
              placeholder="请输入题干"
              clearable
            ></el-input>

            <el-select
              style="width: 160px"
              @change="getList(false)"
              class="search"
              v-model="queryParams.difficulty"
              placeholder="请选择难度"
              clearable
            >
              <el-option
                v-for="dict in dict.type.topic_difficulty"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>

            <el-button
              icon="el-icon-refresh"
              type="primary"
              size="mini"
              @click="resetQuery"
              >重置</el-button
            >
            <el-button
              type="primary"
              icon="el-icon-view"
              @click="handlePreview"
              size="medium"
              >题库预览</el-button
            >
          </div>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
                v-hasPermi="['exam:topic:add']"
                >新增
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="el-icon-upload"
                size="mini"
                @click="showUploadDialog"
                v-hasPermi="['exam:topic:import']"
                >批量导入试题
              </el-button>
            </el-col>
            <!--        <el-col v-if="showExpot" :span="1.5">-->
            <!--          <el-button type="info" plain icon="el-icon-download" size="mini" @click="handleExport"-->
            <!--                     v-hasPermi="['exam:topic:export']">导出-->
            <!--          </el-button>-->
            <!--        </el-col>-->
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                :disabled="multiple"
                @click="handleDelete"
                v-hasPermi="['exam:topic:remove']"
                >删除
              </el-button>
            </el-col>
          </el-row>

          <el-table
            v-loading="loading"
            ref="topicListTable"
            :data="topicList"
            :show-overflow-tooltip="true"
            @selection-change="handleSelectionChange"
            height="500"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="类型" align="center" prop="searchWord">
              <template slot-scope="scope">
                {{ scope.row.searchWord }}
              </template>
            </el-table-column>
            <el-table-column label="题型" align="center" prop="topicType">
              <template slot-scope="scope">
                {{ returnTopicType(scope.row.topicType) }}
              </template>
            </el-table-column>
            <el-table-column
              label="题干"
              align="center"
              prop="content"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="答案"
              align="center"
              prop="answer"
              :show-overflow-tooltip="true"
            />
            <el-table-column label="难度" align="center" prop="difficulty">
              <template slot-scope="scope">
                {{ returnDifficulty(scope.row.difficulty) }}
              </template>
            </el-table-column>
            <!-- <el-table-column label="分值" align="center" prop="score" /> -->
            <el-table-column
              label="启用状态"
              align="center"
              prop="status"
              v-if="!this.hiddenEdit"
            >
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.status"
                  @change="handleStatus(scope.row)"
                  active-color="#ff4949"
                  inactive-color="#13ce66"
                  :active-value="1"
                  :inactive-value="0"
                ></el-switch>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['exam:topic:edit']"
                  >修改
                </el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['exam:topic:remove']"
                  >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div
            style="
              width: 100%;
              display: flex;
              justify-content: flex-end;
              padding: 10px;
              box-sizing: border-box;
            "
          >
            共 {{ total }} 条
          </div>
          <!--          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"-->
          <!--                      :limit.sync="queryParams.pageSize" @pagination="getList()"/>-->
          <!-- 添加或修改试题对话框 -->
          <el-dialog
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            :title="title"
            :visible.sync="open"
            width="70vw"
            append-to-body
          >
            <TopicForm
              @cancel="cancel"
              :isOfflineExam="isOfflineExam"
              :showAll="showAll"
              :cid="cid"
              :needTitleId="false"
              :propsCategoryId="propsCategoryId"
              ref="myTopicForm"
              @handleClose="handleClose"
            />
          </el-dialog>
          <!-- 添加或修改试题对话框 -->
          <el-dialog
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            title="已选题目"
            :visible.sync="showSelect"
            width="800px"
            append-to-body
          >
            <el-table
              :data="arrTotal"
              :show-overflow-tooltip="true"
              height="500"
            >
              <el-table-column
                label="题型"
                align="center"
                prop="topicType"
                min-width="5%"
              >
                <template slot-scope="scope">
                  {{ returnTopicType(scope.row.topicType) }}
                </template>
              </el-table-column>
              <el-table-column
                label="题干"
                align="center"
                prop="content"
                min-width="25%"
                :show-overflow-tooltip="true"
              />
              <el-table-column
                label="答案"
                align="center"
                prop="answer"
                min-width="15%"
                :show-overflow-tooltip="true"
              />
              <el-table-column
                label="难度"
                align="center"
                prop="difficulty"
                min-width="5%"
              >
                <template slot-scope="scope">
                  {{ returnDifficulty(scope.row.difficulty) }}
                </template>
              </el-table-column>
              <el-table-column
                label="分值"
                align="center"
                prop="score"
                min-width="5%"
              />
              <el-table-column
                label="启用状态"
                align="center"
                prop="status"
                min-width="5%"
                v-if="!this.hiddenEdit"
              >
                <template slot-scope="scope">
                  <el-switch
                    v-model="scope.row.status"
                    @change="handleStatus(scope.row)"
                    active-color="#ff4949"
                    inactive-color="#13ce66"
                    :active-value="1"
                    :inactive-value="0"
                  ></el-switch>
                </template>
              </el-table-column>
            </el-table>
          </el-dialog>
          <!--  批量上传试题对话框  -->
          <el-dialog
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            title="批量导入试题"
            :visible.sync="uploadDialog"
            width="70vw"
            append-to-body
          >
            <div class="upload_total" v-if="!showChecked">
              <div class="up_excel_all">
                <img
                  @click="downLoadExcel"
                  class="up_excel"
                  src="@/assets/images/up_excel.png"
                  alt=""
                />
                <el-link @click="downLoadExcel" class="link_txt" type="success"
                  >下载EXCEL模板</el-link
                >
              </div>
              <upload-excel @uploadFiles="uploadFiles"></upload-excel>
            </div>
            <div style="width: 100%" v-if="showChecked">
              <div class="checked_box">
                <div class="checked_box_left" :class="{ w_100: !showRight }">
                  <div class="btns_operation">
                    <div>
                      知识点
                      <el-cascader
                        v-model="model.exportCategoryId"
                        :options="exportCategoryTree"
                        filterable
                        clearable
                        :props="{ expandTrigger: 'hover', checkStrictly: true }"
                        @change="handleNodeClick"
                      />
                    </div>
                    <el-button
                      @click="switchShowChecked"
                      type="primary"
                      plain
                      icon="el-icon-upload"
                      size="small"
                      >重新上传文件</el-button
                    >
                  </div>
                  <div class="detection_connect">
                    <div
                      class="detection_item"
                      v-for="(item, index) in valiDate.topicEntityList"
                      :key="index"
                    >
                      <div class="topic_item">
                        {{ item.topic.topicContent }}
                      </div>
                      <div
                        v-if="
                          item.topic.topicType == '单选题' ||
                          item.topic.topicType == '多选题'
                        "
                      >
                        <div class="topic_item">A.{{ item.topic.optionA }}</div>
                        <div class="topic_item">B.{{ item.topic.optionB }}</div>
                        <div class="topic_item">C.{{ item.topic.optionC }}</div>
                        <div class="topic_item">D.{{ item.topic.optionD }}</div>
                      </div>
                      <div
                        v-if="item.topic.topicType == '多选题'"
                        class="topic_item"
                      >
                        E.{{ item.topic.optionE }}
                      </div>
                      <div v-if="item.topic.topicType == '判断题'">
                        <div class="topic_item">A.正确</div>
                        <div class="topic_item">B.错误</div>
                      </div>
                      <div class="topic_item">答案:{{ item.topic.answer }}</div>
                      <div class="topic_item">
                        题型:{{ item.topic.topicType }}
                      </div>
                      <div class="topic_item">分数:{{ item.topic.score }}</div>
                      <div class="topic_item">
                        分类:{{ item.topic.category }}
                      </div>
                      <div class="success_prompt" v-if="item.type == 'success'">
                        <div><i class="el-icon-info"></i> 提示信息</div>
                        <div>上传成功</div>
                      </div>
                      <div class="warning_prompt" v-if="item.type == 'warning'">
                        <div><i class="el-icon-info"></i> 提示信息</div>
                        <div>{{ item.msg }}</div>
                      </div>
                      <div class="error_prompt" v-if="item.type == 'error'">
                        <div><i class="el-icon-info"></i> 提示信息</div>
                        <div>{{ item.msg }}</div>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="checked_box_right" v-if="showRight">
                  <div class="btns_operation">
                    <el-button
                      @click="showRight = false"
                      icon="el-icon-close"
                      size="small"
                    >
                      隐藏消息框</el-button
                    >
                  </div>
                  <div class="detection_connect">
                    <div
                      v-if="wrainingNum > 0 || errorNum > 0"
                      class="connect_info"
                    >
                      检查完毕，共检测到
                      <span>{{ wrainingNum + errorNum }}</span> 道试题
                    </div>
                    <div v-if="errorNum > 0" class="connect_txt color_red">
                      有 <span>{{ errorNum }}</span> 道试题格式错误
                    </div>
                    <div
                      v-if="wrainingNum > 0"
                      class="connect_txt color_orange"
                    >
                      有 <span>{{ wrainingNum }}</span> 道试题在试题库中已重复
                    </div>

                    <div class="title color_red" v-if="errorNum > 0">
                      ---------------以下 <span>{{ errorNum }}</span
                      >试题格式错误，请检查并修正---------------
                    </div>
                    <div
                      class="detection_item"
                      v-for="(item, index) in valiDate.topicEntityList"
                      :key="index"
                    >
                      <div
                        class="error_total color_red"
                        v-if="item.type == 'error'"
                      >
                        <div>
                          第{{ index + 1 }}题：{{ item.msg }} 试题：{{
                            item.topic.topicContent
                          }}
                        </div>
                      </div>
                    </div>

                    <div class="title color_orange" v-if="wrainingNum > 0">
                      ---------------以下 <span>{{ wrainingNum }}</span
                      >试题在试题库中已重复，无法导入---------------
                    </div>
                    <div
                      class="detection_item"
                      v-for="(item, index) in valiDate.topicEntityList"
                      :key="item.topic.topicContent"
                    >
                      <div
                        class="warning_total color_orange"
                        v-if="item.type == 'warning'"
                      >
                        <div>
                          第{{ index + 1 }}题：{{ item.msg }} 试题：{{
                            item.topic.topicContent
                          }}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="btns_bottom">
                <!-- <el-button
                  @click="importTopic(1)"
                  type="primary"
                  plain
                  icon="el-icon-upload"
                  size="small"
                  >导入</el-button
                > -->
                <!--            <el-button @click="importTopic(2)"  type="warning" plain icon="el-icon-upload" size="small">全部导入，并覆盖重复试题</el-button>-->
                <el-button
                  @click="importTopic(3)"
                  type="primary"
                  plain
                  icon="el-icon-upload"
                  size="small"
                  >导入</el-button
                >
              </div>
            </div>
          </el-dialog>
        </div>
      </div>
    </div>
    <examPreview ref="exampreview"></examPreview>
    <input
      style="display: none"
      class="uploadContain_input"
      type="file"
      accept=".gif, .png, .jpeg,  .jpg,  .mp4, .webm, .pdf, .docx, .doc, .rtf, .pptx, .ppt,  .xls, .xlsx ,.wps ,.ofd
        ,.txt ,.js ,.json ,.css ,.sql ,.xml ,.java ,.cs(c#)"
      ref="fileInput"
      @change="uploadFile($event)"
      multiple
    />
  </div>
</template>


<script>
import examPreview from "@/views/course/components/examPreview.vue";
import {
  listTopic,
  delTopic,
  updateTopic,
  importValidate,
  importTopic,
} from "@/api/exam/topic";

import {
  getTopicCategoryTree,
  addTopicCategory,
  delTopicCategoryAndChild,
  updateTopicCategory,
  getTopicCategoryName,
} from "@/api/exam/topicCategory";

import TopicForm from "./TopicForm";

import uploadExcel from "@/components/uploadExcel/uploadExcel";

export default {
  name: "TopicList",
  dicts: ["topic_type", "topic_difficulty"],
  props: {
    titleId: {},
    hideAdd: {},
    hiddenEdit: {},
    propsCategoryId: {
      type: [String, Number],
      required: false,
    },
    taskId: {
      type: [String, Number],
      required: false,
    },
    isOfflineExam: {
      type: [Boolean],
      required: false,
    },
    showAll: {
      type: [Boolean],
      required: false,
    },
    showExpot: {
      type: [Boolean],
      required: false,
    },
    parentopen: {
      type: [Boolean],
      required: false,
    },
  },
  components: { TopicForm, uploadExcel, examPreview },
  data() {
    return {
      operationType: "",
      cid: null,
      showSelect: false,
      selectedId: "",
      activeName: "1",
      //是否展示检验结果
      showChecked: false,
      //上传试题弹框
      uploadDialog: false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 弹出层主键
      topicId: 0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      arrTotal: [],
      // 试题表格数据
      topicList: [],
      // 查询参数
      queryParams: {
        searchWord: "",
        pageNum: 1,
        pageSize: 9999999,
        categoryId: null,
        topicType: null,
        difficulty: null,
        titleId: 0,
        containerId: 0,
      },
      //分类树
      categoryTree: [],
      paddingStyle: "",
      // 校验 结果
      valiDate: null,
      //检验试题统计
      wrainingNum: 0,
      errorNum: 0,
      showRight: true,
      //默认选项
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 判断节点是否能被编辑
      categoryTreeEdit: false,
      categoryId: null,
      model: {
        categoryId: "",
        exportCategoryId: "",
      },
    };
  },
  computed: {
    dateRange() {
      let { selectedId, ids } = this;
      return { selectedId, ids };
    },
  },
  watch: {
    propsCategoryId(e) {
      console.log("topicList_propsCategoryId", e);
    },
    parentopen: {
      immediate: true,
      handler(val) {
        if (val) {
          this.queryParams.categoryId = "";
          this.showChecked = false;
          this.cid = null;
          this.refreshCategoryTree();
        }
      },
    },
    dateRange: {
      immediate: true,
      deep: true,
      handler(val) {
        if (this.categoryTree && this.categoryTree.length > 0) {
          for (const valElement of this.categoryTree) {
            if (this.selectedId == valElement.value) {
              if (valElement.selectIds.length > 0) {
                if (this.topicList.length == valElement.selectIds.length) {
                  valElement.checkAll = true;
                  valElement.isIndeterminate = false;
                } else {
                  valElement.checkAll = false;
                  valElement.isIndeterminate = true;
                }
              } else {
                valElement.checkAll = false;
                valElement.isIndeterminate = false;
              }
            }
            if (valElement.children && valElement.children.length > 0) {
              for (const childItem of valElement.children) {
                if (this.selectedId == childItem.value) {
                  console.log(
                    this.topicList.length,
                    "this.topicList.length",
                    this.ids.length
                  );
                  if (childItem.selectIds.length > 0) {
                    if (this.topicList.length == childItem.selectIds.length) {
                      childItem.checkAll = true;
                      childItem.isIndeterminate = false;
                    } else {
                      childItem.checkAll = false;
                      childItem.isIndeterminate = true;
                    }
                  } else {
                    childItem.checkAll = false;
                    childItem.isIndeterminate = false;
                  }
                }
              }
            }
          }
        }
      },
    },
    categoryTree: {
      immediate: true,
      deep: true,
      handler(val) {
        let arr = [];
        if (val && val.length > 0) {
          for (const valElement of val) {
            if (valElement.selectIds.length > 0) {
              arr = arr.concat(valElement.selectIds);
            }
            if (valElement.children && valElement.children.length > 0) {
              for (const childItem of valElement.children) {
                if (childItem.selectIds.length > 0) {
                  arr = arr.concat(childItem.selectIds);
                }
              }
            }
          }
        }
        const newArr = Array.from(
          new Set(arr.map((item) => JSON.stringify(item)))
        ).map((item) => JSON.parse(item));
        console.log(newArr);
        this.arrTotal = newArr;
      },
    },
  },
  created() {},
  methods: {
    /* 题库预览 */
    handlePreview() {
      this.$refs.exampreview.show(3, 0, "topic", this.topicList);
    },
    changeAllSelection(item) {
      if (item.value != this.selectedId) {
        return;
      }
      if (item.checkAll) {
        if (
          item.selectIds.length != this.topicList.length ||
          item.selectIds.length == 0
        ) {
          this.$refs.topicListTable.toggleAllSelection();
        }
      } else {
        if (!item.isIndeterminate) {
          this.$refs.topicListTable.clearSelection();
        }
      }
    },
    changeSelected(item, type) {
      this.cid = item.value;
      console.log(item, type);
      this.selectedId = item.value;
      this.queryParams.categoryId = item.value;
      this.getList(item);
    },
    /**分类节点点击事件 */
    handleNodeClick(value) {
      if (value && value.length > 0) {
        this.categoryId = value[value.length - 1];
      }
    },
    /**增加分类节点 */
    appendNode(data) {
      console.log(data);
      addTopicCategory({
        parentId: data.value,
        name: "新增子目录",
      }).then((res) => {
        if (res.code === 200) {
          const newChild = {
            value: res.data,
            label: "新增子目录",
            edit: false,
          };
          if (!data.children) {
            this.$set(data, "children", []);
          }
          data.children.push(newChild);
          this.refreshCategoryTree();
        } else {
          this.$message.error({
            message: res.msg,
            showClose: true,
          });
        }
      });
    },
    /**删除节点 */
    removeNode(node, data) {
      // 判断该节点是否有子节点
      if (node.childNodes.length != 0) {
        this.$message({
          message: "该节点下存在子节点，不允许直接删除",
          type: "warning",
        });
        return;
      }
      delTopicCategoryAndChild(data.value).then((res) => {
        if (res.code === 200) {
          this.refreshCategoryTree();
        } else {
          this.$message.error({
            message: res.msg,
            showClose: true,
          });
        }
      });
    },
    /**编辑节点 */
    editNode(node, data) {
      //如果有其他节点在编辑则不响应
      if (this.categoryTreeEdit) {
        return;
      }
      this.$set(data, "edit", true);
      this.categoryTreeEdit = true;
      this.$nextTick(function () {
        this.$refs.inputVal.focus();
      });
    },
    /**保存节点 */
    updateNode(node, data) {
      updateTopicCategory({ id: data.value, name: data.label }).then((res) => {
        if (res.code === 200) {
          this.$set(data, "edit", false);
          this.categoryTreeEdit = false;
          this.refreshCategoryTree();
          this.handleNodeClick(data);
        } else {
          this.$message.error({
            message: res.msg,
            showClose: true,
          });
        }
      });
    },
    //取消
    cancelEdit(data) {
      data.edit = !data.edit;
      this.categoryTreeEdit = false;
    },

    //重新上传
    switchShowChecked() {
      this.$confirm("确定要重新上传吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // this.showChecked = false;
          this.$refs.fileInput.click();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
            showClose: true,
          });
        });
    },
    //导入试题
    importTopic(status) {
      if (
        !this.model.exportCategoryId ||
        this.model.exportCategoryId.length == 0
      ) {
        this.categoryId = this.propsCategoryId;
      }
      let obj = {
        1: "确定全部重新导入吗",
        2: "确定全部导入，并覆盖重复试题吗",
        3: "确定只导入新试题吗",
      };
      this.$confirm(obj[status], "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const loading = this.$loading({
            lock: true,
            text: "正在导入中…",
            spinner: "el-icon-loading",
            background: "rgba(255, 255, 255, 0.6)",
          });
          let res;
          try {
            res = await importTopic(
              status,
              this.categoryId,
              this.valiDate.ccTopicList
            );
          } catch (e) {
            console.error(e);
          }
          if (res) {
            loading.close();
            this.$message.success({ message: "导入成功！", showClose: true });
            this.getList();
            this.uploadDialog = false;
          } else {
            loading.close();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
            showClose: true,
          });
        });
    },
    downLoadExcel() {
      let url =
        "https://zy-metaxun.oss-cn-hangzhou.aliyuncs.com/zhiying/template/%E6%A8%A1%E6%9D%BF1%EF%BC%9A%E8%AF%95%E9%A2%98%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF%20.xls";
      window.open(url);
    },
    async uploadFile(event) {
      let files = event.target.files;
      let formData = new FormData();
      formData.append(
        "file",
        new File([Array.from(files)[0]], Array.from(files)[0].name)
      );
      this.uploadFiles(formData);
      event.target.value = "";
    },
    async uploadFiles(formData) {
      if (
        !this.model.exportCategoryId ||
        this.model.exportCategoryId.length == 0
      ) {
        this.categoryId = this.propsCategoryId;
      }
      formData.append("categoryId", this.categoryId);
      if (this.operationType == 5 || this.operationType == 6) {
        formData.append("categoryType", 1);
      }

      if (formData) {
        const loading = this.$loading({
          lock: true,
          text: "上传试题检验中…",
          spinner: "el-icon-loading",
          background: "rgba(255, 255, 255, 0.6)",
        });
        let res;
        console.log(formData);
        try {
          res = await importValidate(formData);
        } catch (e) {
          console.error(e);
        }
        if (res) {
          loading.close();
          this.valiDate = res.data;
          let wrainingNum = 0;
          let errorNum = 0;
          res.data.topicEntityList.forEach((item, value) => {
            console.log(item);
            if (item.type == "warning") {
              wrainingNum++;
            }
            if (item.type == "error") {
              errorNum++;
            }
          });
          this.wrainingNum = wrainingNum;
          this.errorNum = errorNum;
          this.showChecked = true;
        } else {
          loading.close();
        }
      }
    },
    showUploadDialog() {
      this.uploadDialog = true;
      this.model.exportCategoryId = "";
      this.valiDate.topicEntityList = [];
      this.wrainingNum = 0;
      this.errorNum = 0;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.refreshCategoryTree();
    },
    /**刷新分类树 */
    refreshCategoryTree() {
      console.log("刷新分类树", this.propsCategoryId);
      this.categoryTree = [];
      this.selectedId = this.propsCategoryId;
      getTopicCategoryTree(this.propsCategoryId).then((res) => {
        if (res.code === 200) {
          this.exportCategoryTree = res.data;
          let arr = [];
          for (const item of res.data[0].children) {
            let obj = {
              ...item,
              checkAll: false,
              isIndeterminate: false,
              disabled: false,
              selectIds: [],
              children: [],
            };
            if (item.children && item.children.length > 0) {
              for (const child of item.children) {
                let childObj = {
                  ...child,
                  checkAll: false,
                  isIndeterminate: false,
                  selectIds: [],
                  disabled: false,
                };
                obj.children.push(childObj);
              }
            }
            arr.push(obj);
          }
          this.categoryTree = arr;
          let obj = {
            ...res.data[0],
            checkAll: false,
            isIndeterminate: false,
            disabled: false,
            selectIds: [],
            children: [],
          };
          this.categoryTree.unshift(obj);
          let arrs = [];
          for (const categoryTreeElement of this.categoryTree) {
            arrs.push(categoryTreeElement.value);
            if (
              categoryTreeElement.children &&
              categoryTreeElement.children.length > 0
            ) {
              for (const child of categoryTreeElement.children) {
                arrs.push(child.value);
              }
            }
          }
          this.activeName = arrs;
        } else {
          this.$message.error({
            message: res.msg,
            showClose: true,
          });
        }
      });
    },
    /**修改启动状态*/
    handleStatus(row) {
      console.log(row.status);
      this.$confirm("确认修改状态？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          updateTopic({ id: row.id, status: row.status }).then((res) => {
            this.$message({
              type: "success",
              message: "修改成功!",
            });
            this.getList();
          });
        })
        .catch(() => {});
    },
    /**返回试题类型 */
    returnTopicType(type) {
      return this.dict.type.topic_type.find((item) => item.value === type + "")
        .label;
    },
    /**返回难度 */
    returnDifficulty(difficulty) {
      return this.dict.type.topic_difficulty.find(
        (item) => item.value === difficulty + ""
      ).label;
    },
    /** 查询试题列表 */
    getList(item) {
      this.topicList = [];
      this.loading = true;
      if (!this.queryParams.categoryId) {
        this.queryParams.categoryId = this.propsCategoryId;
      }
      //if (this.isOfflineExam) {
      //  this.queryParams.topicType = "5";
      //} else {
      //  if (this.queryParams.topicType == "5") {
      //    this.queryParams.topicType = "";
      //  }
      //}
      console.log(
        "查询试题列表",
        this.queryParams.categoryId,
        this.propsCategoryId
      );
      listTopic(this.queryParams).then((response) => {
        // if (!this.isOfflineExam && !this.showAll) {
        //   for (const row of response.rows) {
        //     if (row.topicType != 5) {
        //       this.topicList.push(row);
        //     }
        //   }
        //   this.total = this.topicList.length;
        // } else {
        this.topicList = response.rows;
        this.total = response.total;
        // }
        // if (item){
        //   if (this.topicList.length==0){
        //     item.disabled=true
        //   }else {
        //     item.disabled=false
        //   }
        // }
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.topicType = "";
      this.queryParams.content = "";
      this.queryParams.difficulty = "";
      this.queryParams.searchWord = "";
      this.handleQuery();
    },
    /** 多选框选中数据*/
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      let selectIds = selection.map((item) => item);

      for (const valElement of this.categoryTree) {
        if (this.selectedId == valElement.value) {
          valElement.selectIds = selectIds;
        }
        if (valElement.children && valElement.children.length > 0) {
          for (const childItem of valElement.children) {
            if (this.selectedId == childItem.value) {
              childItem.selectIds = selectIds;
            }
          }
        }
      }
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /**确认添加 */
    handleSelect() {
      if (this.arrTotal.length === 0) {
        this.$modal.msgWarning("请选择试题");
        return;
      }
      const loading = this.$loading({
        lock: true,
        text: "正在添加...",
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.6)",
      });
      let ids = this.arrTotal.map((item) => item.id);
      this.$emit(
        "handleSelect",
        ids,
        this.queryParams.titleId,
        this.queryParams.containerId,
        loading
      );
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('确定删除试题编号为"' + ids + '"的数据项？')
        .then(function () {
          return delTopic(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    handleAdd() {
      this.open = true;
      this.title = "添加试题";
      this.$nextTick(() => {
        this.$refs.myTopicForm.reset(0, 0);
      });
    },
    handleUpdate(row) {
      this.open = true;
      this.title = "修改试题";
      const id = row.id || this.ids;
      this.$nextTick(() => {
        this.$refs.myTopicForm.getTopicInfo(id, 0, 0);
      });
    },
    /** 导出按钮操作 */
    handleExport(queryParams) {
      console.log(queryParams, "queryParams");
      let ids;
      if (this.ids.length > 0) {
        ids = this.ids.join(",");
      } else {
        ids = "all";
      }
      this.download(
        "exam/topic/export",
        {
          ...queryParams,
          propsCategoryId: this.propsCategoryId,
          ids,
        },
        `topic_${new Date().getTime()}.xlsx`
      );
    },
    /**关闭弹出层 */
    handleClose(topicId, titleId) {
      this.open = false;
      this.getList();
      // this.refreshCategoryTree();
    },
    /**加载试题列表页面 */
    loadTopicList(titleId, containerId, operationType) {
      this.operationType = operationType;
      this.arrTotal = [];
      this.refreshCategoryTree();
      console.log(titleId, containerId);
      if (titleId > 0) {
        this.queryParams.titleId = titleId;
      }
      if (containerId > 0) {
        this.queryParams.containerId = containerId;
      }
      this.getList();
    },
  },
};
</script>

<style scoped lang="scss">
.topiclist_content {
  width: 100%;
  display: flex;
  background: white;
  &_left {
    width: 420px;
    height: 550px;
    overflow: auto;
    .tree_parent {
      width: 100%;
      padding: 0 30px;
      box-sizing: border-box;
      height: 35px;
      display: flex;
      align-items: center;
    }
    .tree_child {
      width: 100%;
      cursor: pointer;
      padding-left: 56px;
      box-sizing: border-box;
      height: 35px;
      display: flex;
      align-items: center;
    }
  }
  &_right {
    flex: 1;
    margin-left: 10px;
    height: 550px;
  }
}

::v-deep .el-tooltip__popper {
  font-size: 14px;
  max-width: 550px;
  overflow: hidden;
}

.myTopicList {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  height: 100%;
}

.upload_total {
  display: flex;
  flex-direction: column;
  width: 100%;
  min-height: 680px;
  padding-bottom: 200px;
  box-sizing: border-box;
}

.link_txt {
  width: 110px;
  margin: 10px auto;
}
.checked_box {
  width: 100%;
  display: flex;
  justify-content: space-between;
  &_left {
    width: 49%;
    background: white;
    .btns_operation {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .detection_connect {
      width: 100%;
      padding: 16px;
      height: 600px;
      overflow: auto;
      box-sizing: border-box;
      border: 1px solid #f3f3f3;
      .detection_item {
        padding: 8px;
        box-sizing: border-box;
        margin-bottom: 10px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      }
    }
  }
  &_right {
    width: 49%;
    background: white;
    .detection_connect {
      width: 100%;
      padding: 16px;
      height: 600px;
      overflow: auto;
      box-sizing: border-box;
      border: 1px solid #f3f3f3;
      .connect_info {
        font-size: 16px;
        font-weight: 500;
        span {
          font-weight: bold;
          font-size: 18px;
        }
      }
      .connect_txt {
        font-size: 14px;
        font-weight: 500;
        span {
          font-weight: bold;
          font-size: 16px;
        }
      }
      .detection_item {
      }
    }
  }
}
.topic_item {
  font-size: 14px;
  font-weight: 500;
  color: #676665;
}
.success_prompt {
  width: 100%;
  color: #1ab394;
  background: #f0f9eb;
  padding: 6px;
  box-sizing: border-box;
  border-radius: 4px;
  margin: 4px 0;
}
.warning_prompt {
  width: 100%;
  color: #f39f6c;
  background: #f9eadc;
  padding: 6px;
  box-sizing: border-box;
  border-radius: 4px;
  margin: 4px 0;
}
.error_prompt {
  width: 100%;
  color: #f56c6c;
  background: #fde6e6;
  padding: 6px;
  box-sizing: border-box;
  border-radius: 4px;
  margin: 4px 0;
}
.btns_bottom {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 16px 0 0;
  box-sizing: border-box;
}
.up_excel_all {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
}
.up_excel {
  width: 60px;
  height: 60px;
  margin: 0 auto;
}
.color_red {
  color: #fb1b23;
}
.color_orange {
  color: #f18e3b;
}
.title {
  margin-top: 20px;
  span {
    font-weight: bold;
    margin: 0 4px;
    font-size: 16px;
  }
}
.w_100 {
  width: 100% !important;
}

.topicForm {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.formFooter {
  box-sizing: inherit;
  text-align: right;
  -webkit-font-smoothing: antialiased;
  text-rendering: optimizeLegibility;
  font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB,
    Microsoft YaHei, Arial, sans-serif;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  height: 32px;
}

.show-hide:hover :nth-child(2) {
  display: inline-block !important;
}

::v-deep .el-input--mini .el-input__inner {
  height: 25px;
  text-align: center;
  line-height: 25px;
}

.select_bg {
  background: #ebfaf9;
}
.search {
  width: 240px;
  margin-right: 10px;
}
.tree_top {
  padding-left: 10px !important;
}
.arrow90 {
  transform: rotate(0) !important;
}

.arrow {
  transition: all 0.5s;
  transform: rotate(-90deg);
  width: 16px;
  height: 16px;
  margin-right: 8px;
}
.arrows {
  transition: all 0.5s;
  width: 16px;
  height: 16px;
  margin-right: 8px;
}
</style>
